/*
 * uploader.cpp
 *
 *  Created on: May 24, 2010
 *      Author: deroy2
 */

#include <QApplication>
#include <QStringList>
#include <QFile>
#include <QTimer>
#include <QList>
#include <QDebug>
#include <QString>
#include <QMessageBox>
#include <QXmlInputSource>
#include <QTextStream>
#include "QCalEventRetriever.h"
//#include "ParseEventDetailsXML.h"

QCalEventRetriever::QCalEventRetriever(QWidget *parent)
	    : QObject(parent)
    
{ 
	manager = new QNetworkAccessManager(this);
	connect(manager, SIGNAL(finished(QNetworkReply*)),this,SLOT(downloadingCompleted(QNetworkReply*)));
}

QCalEventRetriever::~QCalEventRetriever()
{
	file->close();
	delete manager, manager=0;
	
}

void QCalEventRetriever::close()
{
    

    disconnect(manager, 0, this, 0);
    QCoreApplication::removePostedEvents(this, QEvent::MetaCall);

    delete manager, manager=0;
    file->close();


}

void QCalEventRetriever::load(const QString& url)
{
	QFile file("c:\\data\\afile.txt");
	file.open(QIODevice::ReadOnly);
	QByteArray page = file.readAll(); 
	if(page.contains("Auth="))
	{
		
		//Get the Auth String
		QString auth(page.data());
		auth = auth.right(auth.length()-auth.indexOf("Auth=")-5);		
		authn = auth.left(auth.indexOf("\n"));
		
//		QFile fp;
//		fp.setFileName("c:\\data\\test1.text");
//		fp.open(QIODevice::WriteOnly | QIODevice::Text);
//		QTextStream out(&fp);
//			out << "GoogleLogin auth="+getAuth();
//			fp.close();
	//	QMessageBox::warning(NULL, "Auth", _auth);]
 
	}	

	
	
	/*QTextStream ts(&file);
	 QChar ch;
	 QString element = "";
	 do{
	 ts >> ch;
	 if(element=="Auth=")
		 {
		 QMessageBox msgBox;
		 msgBox.setText("Auth Found!!");
	     msgBox.exec();
		 }
	 else if (ch == '\r' || ch == '\n' || ch == ' ') {
		 element="";
		 }
	 else{
	 element+=ch;
	 }
	 }while (!ts.atEnd());*/
	QNetworkRequest request(url);
//	QFile fp;
//	fp.setFileName("c:\\data\\test1.text");
//	fp.open(QIODevice::WriteOnly | QIODevice::Text);
//	QTextStream out(&fp);
//	out << "GoogleLogin auth="+authn.trimmed();
//	
//	fp.close();

	request.setRawHeader("Authorization", "GoogleLogin auth="+authn.trimmed().toAscii());
	request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
	QNetworkReply* reply = manager->get(request);
	connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError)));

}

int QCalEventRetriever::tag;
void QCalEventRetriever::downloadingCompleted(QNetworkReply* reply)
{

//        QFile file("c:\\data\\cfile.xml");
//        file.open(QIODevice::ReadOnly);
	
        if(tag==0)
        	{
        QFile file("c:\\data\\PrivateEvent.txt");
        	file.open(QIODevice::ReadWrite | QIODevice::WriteOnly);
        	char buffer[1024];
        		while(true) {
        			qint64 len = reply->read(buffer,1024);
        			if(len < 1) {
        				break;
        			}
        			file.write(buffer,len);
        		}     
        		reply->close();
        		file.close();
        	loadParsed();
        	} 
        else
        	{
			QFile file("c:\\data\\PrivateEvent.xml");
        	file.open(QIODevice::ReadWrite | QIODevice::WriteOnly);
            char buffer[1024];
                while(true) {
                    qint64 len = reply->read(buffer,1024);
                    if(len < 1) {
                        break;
                    }
                    file.write(buffer,len);
                }     
                reply->close();
                file.close();
        
        	}
        	//request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
        	
        	
        	
        	//qDebug("QNetworkReply %X\n",reply);

        	

        		 
	QMessageBox msgBox2;
        msgBox2.setText("upload done");
        msgBox2.exec(); 
        
       emit downloadCompleted();

    qDebug("upload done");
    
}

void QCalEventRetriever::error(QNetworkReply::NetworkError aErr)
{
	
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    QString strerr;
    strerr=QString("Network Error:%1")
    		.arg(aErr);
    QMessageBox msgBoxErr;
     msgBoxErr.setText(strerr);
     msgBoxErr.exec();
    qDebug("Network error:%d \n",aErr);
    qCritical("%s",reply->errorString().toStdString().c_str());
    
}

void QCalEventRetriever::loadParsed()
	{
	QFile file2("c:\\data\\PrivateEvent.txt");
	file2.open(QIODevice::ReadOnly);
	QByteArray page = file2.readAll();
	if(page.contains("A HREF="))
		{
			
			//Get the Auth String
			QString link(page.data());
			link = link.right(link.length()-link.indexOf("gsessionid=")-11);	
			link = link.left(link.indexOf("here")-2);
			
//	        			QString TEST(link);
//	        			TEST =  TEST.left(link.indexOf("here")-2);
			
			QMessageBox msgBoxErr;
				 msgBoxErr.setText(link);
				 msgBoxErr.exec();
			QString url="https://www.google.com/calendar/feeds/default/private/full?gsessionid=";
			
			QNetworkRequest request(url.append(link));
			//request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
			//QByteArray data;
			
			request.setRawHeader("Authorization", "GoogleLogin auth="+authn.trimmed().toAscii());
			//data.append(QString(QString("accountType=GOOGLE") + QString("&Email = debjitroy.dev@gmail.com") + QString("&Passwd= krrish")+ QString("&service=cl") + QString("&source=mycompany-GBlogger-1.0")).toUtf8());
			//QNetworkReply* reply = manager->post(request,data);
			QNetworkReply* reply = manager->get(request);
			connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError)));
			//authn = auth.left(auth.indexOf("\n"));	
		}
	file2.close();
	tag=1;
	        	

	}
